package com.jhx.video.shortvideo.editor.cover

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Point
import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jhx.common.cache.SimpleCache
import com.jhx.common.framework.QuickBaseFragment
import com.jhx.common.model.Video
import com.jhx.common.utils.centerToast
import com.jhx.video.R
import com.jhx.video.shortvideo.editor.VideoEditerWrapper
import com.jhx.video.shortvideo.editor.common.widget.videotimeline.VideoProgressController
import com.jhx.video.videoupload.VideoPublish
import com.tencent.ugc.TXVideoEditConstants
import com.tencent.ugc.TXVideoEditer
import kotlinx.android.synthetic.main.fragment_cover.*

/**
 * 选择封面的fragment
 *
 * @author Jack 2018-03-09 23:43
 */
class CoverFragment : QuickBaseFragment() {
    private var mVideoDuration: Long? = 0L
    private var mCurrentDuration: Long? = 0L
    private var mVideoPath: String? = null
    // 短视频SDK获取到的视频信息
    private var mTXVideoEditer: TXVideoEditer? = null
    private var mVideoProgressController: VideoProgressController? = null
    private val mVideoProgressSeekListener = object : VideoProgressController.VideoProgressSeekListener {
        override fun onVideoProgressSeek(currentTimeMs: Long) {
            img_cover.visibility = View.GONE
            mCurrentDuration = currentTimeMs
            previewAtTime(currentTimeMs)
        }

        override fun onVideoProgressSeekFinish(currentTimeMs: Long) {
            img_cover.visibility = View.GONE
            previewAtTime(currentTimeMs)
        }
    }

    companion object {
        val KEY_VIDEO_PATH = "video_path"
    }

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.fragment_cover, container, false)
    }

    @SuppressLint("MissingSuperCall")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val wrapper = VideoEditerWrapper.getInstance()
        setTitle("选择封面")
        mTXVideoEditer = wrapper.editer
        if (mTXVideoEditer == null || wrapper.txVideoInfo == null) {
            activity.centerToast("状态异常")
            return
        }
        mVideoDuration = mTXVideoEditer?.txVideoInfo?.duration
        mVideoPath = arguments.getString(KEY_VIDEO_PATH)
        initPlayerLayout()
        initVideoProgressLayout()
        initData(1000)
        setMenuText("完成")
    }

    private fun initData(time: Long?) {
        if(time != null && time > 0) {
            val task = object: AsyncTask<Long, String, Bitmap>() {
                override fun doInBackground(vararg params: Long?): Bitmap {
                    return VideoPublish(context).getThumb("$mVideoPath", time)
                }

                override fun onPostExecute(result: Bitmap?) {
                    super.onPostExecute(result)
                    if(result != null && result?.byteCount > 0) {
                        img_cover.visibility = View.VISIBLE
                        img_cover.setImageBitmap(result)
                    }
                }
            }
            task.execute()
        }
    }

    private fun initVideoProgressLayout() {
        val point = Point()
        activity.windowManager.defaultDisplay.getSize(point)
        val screenWidth = point.x
        video_progress_view.viewWidth = screenWidth
        // 获取预处理的缩略图集合
        val thumbnailList = VideoEditerWrapper.getInstance().allThumbnails
        video_progress_view.setThumbnailData(thumbnailList)
        if(mVideoDuration != null) {
            mVideoProgressController = VideoProgressController(mVideoDuration!!)
            mVideoProgressController?.setVideoProgressView(video_progress_view)
            mVideoProgressController?.setVideoProgressSeekListener(mVideoProgressSeekListener)
            mVideoProgressController?.setVideoProgressDisplayWidth(screenWidth)
        }

    }

    private fun initPlayerLayout() {
        val param = TXVideoEditConstants.TXPreviewParam()
        param.videoView = fl_cover
        param.renderMode = TXVideoEditConstants.PREVIEW_RENDER_MODE_FILL_EDGE
        mTXVideoEditer?.initWithPreview(param)
    }

    /**
     * 调用mTXVideoEditer.previewAtTime后，需要记录当前时间，下次播放时从当前时间开始
     *
     * @param timeMs
     */
    fun previewAtTime(timeMs: Long) {
        mTXVideoEditer?.pausePlay()
        mTXVideoEditer?.previewAtTime(timeMs)
    }

    override fun onMenuClick(view: View?) {
        super.onMenuClick(view)
        @SuppressLint("StaticFieldLeak")
        val task = object: AsyncTask<Void, String, String>() {
            override fun doInBackground(vararg params: Void): String {
                if(mCurrentDuration != null && mCurrentDuration!! > 0) {
                    return VideoPublish(context).getVideoThumb("$mVideoPath", mCurrentDuration!!)
                }
                return ""
            }

            override fun onPostExecute(result: String?) {
                super.onPostExecute(result)
                SimpleCache.put(Video.COVER_PATH, "$result")
                pop()
            }
        }
        task.execute()
    }

    override fun showToolbar(): Boolean {
        return true
    }

}